#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
工作人员管理API路由
"""

from flask import Blueprint, request, jsonify
from models.staff import Staff
from models.task import Task
from database import db
from utils.decorators import admin_required
from datetime import datetime, timedelta
from sqlalchemy import or_
import jwt

staff_bp = Blueprint('staff', __name__)

@staff_bp.route('/', methods=['GET'])
@admin_required
def get_staff_list(admin):
    """获取工作人员列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        search = request.args.get('search', '')
        position = request.args.get('position', '')
        status = request.args.get('status', '')
        
        query = Staff.query
        
        if search:
            query = query.filter(or_(
                Staff.name.like(f'%{search}%'),
                Staff.staff_no.like(f'%{search}%'),
                Staff.phone.like(f'%{search}%')
            ))
        
        if position:
            query = query.filter(Staff.position == position)
        
        if status:
            query = query.filter(Staff.status == status)
        
        pagination = query.order_by(Staff.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        staff_list = pagination.items
        
        return jsonify({
            'success': True,
            'data': {
                'staff': [staff.to_dict() for staff in staff_list],
                'pagination': {
                    'page': page,
                    'pages': pagination.pages,
                    'per_page': per_page,
                    'total': pagination.total,
                    'has_prev': pagination.has_prev,
                    'has_next': pagination.has_next
                }
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取工作人员列表失败: {str(e)}'}), 500

@staff_bp.route('/', methods=['POST'])
@admin_required
def create_staff(admin):
    """创建工作人员"""
    try:
        data = request.get_json()
        
        # 检查用户名是否已存在
        if Staff.query.filter_by(username=data['username']).first():
            return jsonify({'success': False, 'message': '用户名已存在'}), 400
        
        # 检查工号是否已存在
        if Staff.query.filter_by(staff_no=data['staff_no']).first():
            return jsonify({'success': False, 'message': '员工编号已存在'}), 400
        
        staff = Staff(
            staff_no=data['staff_no'],
            username=data['username'],
            password=data['password'],
            name=data['name'],
            phone=data.get('phone'),
            position=data['position'],
            department=data.get('department'),
            hire_date=datetime.strptime(data['hire_date'], '%Y-%m-%d') if data.get('hire_date') else None
        )
        
        db.session.add(staff)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '工作人员创建成功',
            'data': staff.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'创建工作人员失败: {str(e)}'}), 500

@staff_bp.route('/<int:staff_id>', methods=['PUT'])
@admin_required
def update_staff(admin, staff_id):
    """更新工作人员信息"""
    try:
        staff = Staff.query.get(staff_id)
        if not staff:
            return jsonify({'success': False, 'message': '工作人员不存在'}), 404
        
        data = request.get_json()
        
        if 'name' in data:
            staff.name = data['name']
        if 'phone' in data:
            staff.phone = data['phone']
        if 'position' in data:
            staff.position = data['position']
        if 'department' in data:
            staff.department = data['department']
        if 'status' in data:
            staff.status = data['status']
        if 'work_status' in data:
            staff.work_status = data['work_status']
        
        staff.updated_at = datetime.now()
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '工作人员信息更新成功',
            'data': staff.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'更新工作人员信息失败: {str(e)}'}), 500

@staff_bp.route('/<int:staff_id>', methods=['DELETE'])
@admin_required
def delete_staff(admin, staff_id):
    """删除工作人员"""
    try:
        staff = Staff.query.get(staff_id)
        if not staff:
            return jsonify({'success': False, 'message': '工作人员不存在'}), 404
        
        # 检查是否有未完成的任务
        pending_tasks = Task.query.filter_by(
            staff_id=staff_id, 
            status__in=['pending', 'in_progress']
        ).count()
        
        if pending_tasks > 0:
            return jsonify({'success': False, 'message': f'该员工还有{pending_tasks}个未完成的任务，无法删除'}), 400
        
        db.session.delete(staff)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '工作人员删除成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'删除工作人员失败: {str(e)}'}), 500

@staff_bp.route('/login', methods=['POST'])
def staff_login():
    """工作人员登录"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400
        
        # 查找工作人员
        staff = Staff.query.filter_by(username=username).first()
        if not staff or not staff.verify_password(password):
            return jsonify({'success': False, 'message': '用户名或密码错误'}), 401
        
        if staff.status != 'active':
            return jsonify({'success': False, 'message': '账户状态异常，请联系管理员'}), 403
        
        # 更新登录信息
        staff.last_login_at = datetime.now()
        db.session.commit()
        
        # 生成JWT令牌
        import jwt
        token_payload = {
            'staff_id': staff.id,
            'username': staff.username,
            'position': staff.position,
            'exp': datetime.utcnow() + timedelta(hours=8)
        }
        token = jwt.encode(token_payload, 'billiard-jwt-secret', algorithm='HS256')
        
        return jsonify({
            'success': True,
            'message': '登录成功',
            'data': {
                'token': token,
                'staff': staff.to_dict()
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'登录失败: {str(e)}'}), 500